package com.teradyne.merlin2.ui.client.activitymappers;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.inject.client.AsyncProvider;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.teradyne.merlin2.ui.client.activities.TopMenuActivity;

public class TopActivityMapper implements ActivityMapper {

	private final AsyncProvider<Provider<TopMenuActivity>> topMenuActivityAsyncProvider;
	
	private Activity topMenuActivity = null;

	@Inject
	public TopActivityMapper(AsyncProvider<Provider<TopMenuActivity>> topMenuActivityAsyncProvider) {
		this.topMenuActivityAsyncProvider = topMenuActivityAsyncProvider;
	}

	@Override
	public Activity getActivity(Place place) {
		return topMenuActivityAsyncProvider();
	}

	private Activity topMenuActivityAsyncProvider() {
		topMenuActivityAsyncProvider.get(new AsyncCallback<Provider<TopMenuActivity>>() {
			
			@Override
			public void onSuccess(Provider<TopMenuActivity> result) {
				topMenuActivity = result.get();
			}
			
			@Override
			public void onFailure(Throwable caught) {
				caughtError(caught);				
			}
		});
		return topMenuActivity;
	}
	
	private void caughtError(Throwable caught) {
		Window.alert("There was something wrong in serving your request. Reason: " + caught.getMessage());
	}
}